// 引入 模块
import {
    getAddressPromise,
    resolveAddressPromise,
    rejectAddressPromise
} from '../../utils/address'

const defaultList = [{
        id: '001',
        name: 'Apple'
    },
    {
        id: '002',
        name: 'Banana'
    },
    {
        id: '003',
        name: 'Orange'
    }
]

Page({
    data: {
        fruits: defaultList,
        addressText: '',
    },

    /**
     * 跳转
     */
    jump(e) {
        console.log(e.target.dataset)
        const {
            id,
            name
        } = e.target.dataset
        wx.navigateTo({
            url: `/pages/detail/detail?id=${id}&name=${name}`
        })
    },

    jump2(e) {
        console.log(e.target.dataset)
        const {
            id,
            name
        } = e.target.dataset
        wx.navigateTo({
            url: `/pages/detail/detail?id=${id}&name=${name}`,
            success: (res) => {
                // res.eventChannel 是数据通道对象，可以简单的看成就是 EventBus
                console.log('res', res)

                // 通过 res.eventChannel.on 监听一个事件
                res.eventChannel.on('abcd', (payload) => {
                    console.log('abcd 事件被触发了', payload)
                    const index = this.data.fruits.findIndex(item => item.id === id)
                    this.setData({
                        [`fruits[${index}]`]: {
                            ...this.data.fruits[index],
                            name: payload
                        }
                    })
                })


                res.eventChannel.emit('set', {
                    name: 'adsfadsf',
                    age: 1111,
                    sex: '111D'
                })
            }
        })
    },

    onResolve() {
        resolveAddressPromise('张三')
    },

    onReject() {
        rejectAddressPromise('里斯')
    },

    jump3() {
        // 获取 getAddressPromise
        getAddressPromise().then((value) => {
            console.log('=== then', value)
            this.setData({
                addressText: value
            })
        }).catch((error) => {
            console.log('=== catch', error)
        })


        wx.navigateTo({
            url: '/pages/address/address'
        })
    }
})